package com.ruipengkj.view.reserveView;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;

import com.ruipengkj.ApplicationContext;
import com.ruipengkj.bean.TStockAlarm;
import com.ruipengkj.bean.TStore;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.commons.util.UUID;
import com.ruipengkj.commons.util.Util;
import com.ruipengkj.component.JComboBoxPOJO;
import com.ruipengkj.component.JLabelJComboBoxComponent;
import com.ruipengkj.component.JLabelJTextFieldComponent;
import com.ruipengkj.component.JPanelFlowLayoutComponent;
import com.ruipengkj.component.RPJButtonRoundBlue;
import com.ruipengkj.component.RPJButtonRoundOrager;
import com.ruipengkj.component.RPJButtonWhite;
import com.ruipengkj.component.comboBox.CommodityJComboBoxTableComponent;
import com.ruipengkj.component.jdialog.BorderJPanel;
import com.ruipengkj.component.jdialog.IDialog;
import com.ruipengkj.component.jpanel.RepeatImagePanel;
import com.ruipengkj.factory.ImageFactory;
import com.ruipengkj.model.StockAlarmAddModel;
import com.ruipengkj.service.TStockAlarmService;
import com.ruipengkj.service.TStoreService;

public class StockAlarmAddDialog extends IDialog implements ActionListener{
	private static final long serialVersionUID = 1L;
	
	private JLabelJComboBoxComponent reserveID;//仓库编号Label+TextField
	private String storeID;
	
	private JLabelJComboBoxComponent type;//报警类型
	
	private JButton addButton; //添加行
	private JButton delButton; //删除行
	private JButton saveExitButton; //保存退出
	private JButton saveButton; //保存新增
	private JButton exitButton; //直接退出
	
	private JTable table;
	private JScrollPane tableJsp;
	private StockAlarmAddModel stockAlarmModel;
	
	private TStockAlarmService tStockAlarmService;//库存报警
	private TStoreService tStoreService;//仓库
	private List<TStockAlarm> delList;
	
	public boolean isSuccess = false;
	
	public StockAlarmAddDialog(JDialog jd, String title, boolean b) {
		super(jd, title, b);
		this.init();
		this.initListener();
		this.setSize(900, 600);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
	}
	private void init() {
		tStockAlarmService = BuildSpringApplication.getInstance().getTStockAlarmServiceImpl();
		tStoreService = BuildSpringApplication.getInstance().getTStoreServiceImpl();
		delList = new ArrayList<TStockAlarm>();
		stockAlarmModel = new StockAlarmAddModel();
		table=uiFactory.createRPJTable(stockAlarmModel, this, this, 30, JLabel.CENTER);
		JComboBox cbox = new CommodityJComboBoxTableComponent();
		cbox.setBorder(null);
		TableCellEditor edt = new DefaultCellEditor(cbox);
		TableColumn tc1=table.getColumnModel().getColumn(1);
		tc1.setCellEditor(edt);
		tableJsp=uiFactory.createJScrollPane(table);
		
		JPanel main_jp=new BorderJPanel(new BorderLayout());
		main_jp.setBackground(Util.PANEL_COLOR);
		main_jp.add(this.initTop(), BorderLayout.NORTH);
		main_jp.add(tableJsp, BorderLayout.CENTER);
		main_jp.add(this.initTail(), BorderLayout.SOUTH);
		main_jp.setCursor(Util.CURSOR_DEFAULT);
		
		this.add(main_jp);
	}

	private JPanel initTop() {
		type = new JLabelJComboBoxComponent("报警类型", new String[]{"1.总量报警", "2.任一仓库报警", "3.某一仓库报警"});
		reserveID = new JLabelJComboBoxComponent("仓库名称：", new String[]{}, 188);
		reserveID.getBox().setEnabled(false);
		SwingUtilities.invokeLater(queryStore);
		JLabelJTextFieldComponent operator = new JLabelJTextFieldComponent("  操作人：", 30);
		operator.getText().setText(ApplicationContext.OPERATOR_NAME);
		operator.getText().setEditable(false);
		
		JPanel top_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		top_panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		top_panel.add(type);
		top_panel.add(reserveID);
		top_panel.add(operator);
		return top_panel;
	}
	
	private JPanel initTail() {
		JPanel tail_panel = new RepeatImagePanel(ImageFactory.loadImage(ImageFactory.DIALOG_TOP_BG_2).getImage());
		tail_panel.setLayout(new GridLayout(2, 1));
		
		addButton = new RPJButtonRoundBlue("添加行");
		delButton = new RPJButtonRoundOrager("删除行");
		JPanel jp1 = new JPanelFlowLayoutComponent(new Component[]{
				addButton, delButton
		}, FlowLayout.LEFT);
		
		saveExitButton = new RPJButtonWhite("保存退出(Ctrl+S)");
		saveButton = new RPJButtonWhite("保存新增(Ctrl+I)");
		exitButton = new RPJButtonWhite("直接退出(Ctrl+Q)");
		JPanel jp6 = uiFactory.createFlowJPanel(FlowLayout.RIGHT);
		jp6.add(saveExitButton);
		jp6.add(saveButton);
		jp6.add(exitButton);
		
		tail_panel.add(jp1);
		tail_panel.add(jp6);
		
		return tail_panel;
	}
	
	@Override
	protected java.awt.Dimension getTitleSize() {
		return new Dimension(126, 29);
	};
	
	private void initListener() {
		addButton.addActionListener(this); //添加行
		delButton.addActionListener(this); //删除行
		saveExitButton.addActionListener(this); //保存退出
		saveExitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		saveButton.addActionListener(this); //保存新增
		saveButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
		exitButton.addActionListener(this); //直接退出
		exitButton.registerKeyboardAction(this, KeyStroke.getKeyStroke(KeyEvent.VK_Q, KeyEvent.CTRL_MASK), JComponent.WHEN_IN_FOCUSED_WINDOW);
//		reserveID.getBox().addActionListener(this);
		type.getBox().addActionListener(this);
	}
	
	
	public void showDialog(TStockAlarm tStockAlarm) {
		if(tStockAlarm!=null){
			stockAlarmModel.addList(tStockAlarm);
			this.storeID = tStockAlarm.getStoreID();
			this.type.getBox().setSelectedItem(tStockAlarm.getType());
		}
		this.setVisible(true);
	}
	
	//选择仓库
	private void selectStore() {
		for (int i = reserveID.getBox().getItemCount()-1; i >= 0; --i) {
			JComboBoxPOJO po = (JComboBoxPOJO)reserveID.getBox().getItemAt(i);
			if (po != null && po.getObject() != null) {
				if (((TStore)po.getObject()).getStoreID().equals(storeID)) {
					reserveID.getBox().setSelectedIndex(i);
					return;
				}
			}
		}
	}
	
	private Boolean check() {//检测是否为必填数据是否为空
		List<TStockAlarm> modelList = stockAlarmModel.getTStockAlarmList();
		if (modelList.size() <= 0) {
			JOptionPane.showMessageDialog(null, "请添加数据！");
			return false;
		}
		
		if (type.getBox().getSelectedIndex() == 2) {
			if (reserveID.getBox().getSelectedIndex() == 0) {
				JOptionPane.showMessageDialog(null, "报警类型为：3某一仓库数量达阀值报警，必须填仓库");
				return false;
			}
		}
		
		for (int i = 0; i < modelList.size(); ++i) {
			TStockAlarm tStockAlarm = modelList.get(i);
			if (tStockAlarm.getTCommodity() ==null || tStockAlarm.getTCommodity().getCommodityID().length() == 0) {
				JOptionPane.showMessageDialog(null, "存在商品编号为空的报警！");
				return false;
			}
			if (tStockAlarm.getMinWalve() < 0 && tStockAlarm.getMinWalve() >= 10000) {
				JOptionPane.showMessageDialog(null, "最低阀值不能小于零,且不能大余10000！");
				return false;
			}
			if (tStockAlarm.getMaxWalve() <= 0 || tStockAlarm.getMaxWalve() > 20000 || tStockAlarm.getMaxWalve() <= tStockAlarm.getMinWalve()) {
				JOptionPane.showMessageDialog(null, "最高阀值必须大于零、大于最低阀值,但不能大余20000！");
				return false;
			}
		}
		return true;
	}
	
	private Boolean save() {
		List<TStockAlarm> modelList = stockAlarmModel.getTStockAlarmList();
		int length = modelList.size();
		for(int i = 0; i < length; ++i) {
			try {
				TStockAlarm tStockAlarm = new TStockAlarm();
				tStockAlarm.setTCommodity(modelList.get(i).getTCommodity());
				
				String storeID = "";
				if (reserveID.getBox().getSelectedIndex() != 0) {
					JComboBoxPOJO po = (JComboBoxPOJO)reserveID.getBox().getSelectedItem();
					if (po != null && po.getObject() != null) {
						storeID = ((TStore)po.getObject()).getStoreID();
					}
				}
				tStockAlarm.setStoreID(storeID);
				tStockAlarm.setType(type.getBox().getSelectedItem().toString());
				
				List<TStockAlarm> tStockAlarmList = tStockAlarmService.findService(tStockAlarm);
				if (tStockAlarmList == null || tStockAlarmList.size() == 0) {
					modelList.get(i).setHappenTime(new Date());
					modelList.get(i).setOperator(ApplicationContext.OPERATOR_ID);
					modelList.get(i).setStoreID(storeID);
					modelList.get(i).setType(type.getBox().getSelectedItem().toString());
					tStockAlarmService.saveOrUpdateService(modelList.get(i));
				} else {
					tStockAlarmList.get(0).setMaxWalve(modelList.get(i).getMaxWalve());
					tStockAlarmList.get(0).setMinWalve(modelList.get(i).getMinWalve());
					tStockAlarmList.get(0).setHappenTime(new Date());
					tStockAlarmList.get(0).setOperator(ApplicationContext.OPERATOR_ID);
					tStockAlarmService.saveOrUpdateService(tStockAlarmList.get(0));
				}
			} catch (Exception e1) {
				e1.printStackTrace();
				return false;
			}
		}
		return true;
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		List<TStockAlarm> modelList = stockAlarmModel.getTStockAlarmList();
		if(e.getSource() == addButton) {
			//添加行
			TStockAlarm tStockAlarm=new TStockAlarm();
			tStockAlarm.setAlarmID(UUID.GenUUID15());
			tStockAlarm.setType("1");
			tStockAlarm.setMinWalve(10);
			tStockAlarm.setMaxWalve(100);
			stockAlarmModel.addList(tStockAlarm);
		} else if(e.getSource() == delButton) {
			//删除行
			if(table.getRowCount()>0){
				if (table.getSelectedRow() < 0 || table.getSelectedRow() >= modelList.size()) {
					delList.add(modelList.get(modelList.size()-1));
				} else {
					delList.add(modelList.get(table.getSelectedRow()));
				}
				stockAlarmModel.delRow(table.getSelectedRow());
			}
		} else if(e.getSource() == saveExitButton) {
			//保存退出
			if (check()) {
				if (save()) {
					this.isSuccess = true;
				}
				this.dispose();
			}
		} else if(e.getSource() == saveButton) {
			//保存新增
			if (check()) {
				if (save()) {
					this.isSuccess = true;
					stockAlarmModel.getTStockAlarmList().clear();
					reserveID.getBox().setSelectedIndex(0);
					table.updateUI();
				}
			}
		} else if(e.getSource() == exitButton) {
			if(Util.showConfirmDialog("是否要退出？")==0){
				this.dispose();
			}
		} else if (e.getSource() == type.getBox()) {
			if (type.getBox().getSelectedIndex() == 2) {
				reserveID.getBox().setEnabled(true);
			} else {
				reserveID.getBox().setEnabled(false);
				if (reserveID.getBox().getComponentCount() >= 1)
				reserveID.getBox().setSelectedIndex(0);
			}
		} else {
			super.actionPerformed(e);
		}
	}
	
	//读取仓库数据
	private Runnable queryStore=new Runnable() {
		@Override
		public void run() {
			try {
				reserveID.addElement(new JComboBoxPOJO("所有仓库……"));
				List<TStore> tStoreList = tStoreService.findService(null);
				if (tStoreList != null && tStoreList.size()!=0) {
					int length = tStoreList.size();
					for(int i = 0; i < length; ++i) {
						TStore tStore=tStoreList.get(i);
						reserveID.addElement(new JComboBoxPOJO(tStore.getStoreID(),tStore.getName(),tStore));
					}
					
					if (storeID != null && !storeID.equals("")) {
						selectStore();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
}
